package buy;

import fruit.Fruit;

import java.util.HashMap;
import java.util.Map;
import java.math.BigDecimal;

// 购物车类
public class ShoppingCart {
    // 存储购物车中的水果和对应的斤数
    public final Map<Fruit, Integer> items = new HashMap<>();
    // 促销策略接口
    public PromotionStrategy promotionStrategy = original -> original;

    /**
     * 添加水果到购物车
     * @param fruit 水果对象
     * @param kilograms 水果的斤数
     */
    public void addFruit(Fruit fruit, int kilograms) {
        if (kilograms < 0) {
            throw new IllegalArgumentException("水果斤数为大于等于 0 的整数");
        }
        items.merge(fruit, kilograms, Integer::sum);
    }

    /**
     * 设置促销策略
     * @param promotionStrategy 促销策略对象
     */
    public void setPromotionStrategy(PromotionStrategy promotionStrategy) {
        this.promotionStrategy = promotionStrategy;
    }

    public BigDecimal calculateTotal() {
        BigDecimal subtotal = items.entrySet().stream()
                .map(entry -> entry.getKey().calculateCost(entry.getValue()))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        return promotionStrategy.applyPromotion(subtotal);
    }
}